﻿using System;
using System.Data.SQLite;

namespace CompactMapper.Orm.UnitOfWork.Mappings
{
    internal class DatabaseCreation
    {
        private const String ReleaseNumberTable = "REVISION";
        private const String CreateReleaseNumberTableText = "CREATE TABLE REVISION( RELEASE_NUMBER CHAR(20) )";
        private const String InsertReleaseNumberText = "INSERT INTO REVISION(RELEASE_NUMBER) VALUES ({0})";


        internal static void CreateDatabase(String connectionString, IMappings mappings)
        {
            using (var connectionWrapper = ConnectionFactory.CreateConnection(connectionString))
            {
                if (TableExists(connectionWrapper.Connection, ReleaseNumberTable))
                    return;
                CreateReleaseNumberTable(connectionWrapper.Connection);
                mappings.RunCreate(connectionWrapper.Connection);
            }
        }

        private static Boolean TableExists(SQLiteConnection connection, String tableName)
        {
            var rows = connection.GetSchema("Tables").Select(String.Format("Table_Name = '{0}'", tableName));
            return rows.Length > 0;
        }

        private static void CreateReleaseNumberTable(SQLiteConnection connection)
        {
            var cmd = new SQLiteCommand(CreateReleaseNumberTableText, connection);
            cmd.ExecuteNonQuery();
            cmd = new SQLiteCommand(String.Format(InsertReleaseNumberText, "'aVersion'"), connection);
            cmd.ExecuteNonQuery();
        }
    }
}